<template>
  <div>
    <el-input
      ref="categorySelect"
      v-model="categoryName"
      placeholder="请选择品类"
      @focus="showCategoryDialog"
      suffix-icon="el-icon-search"
      :disabled="disabled"
    />
    <basic-dialog
      width="60%"
      title="选择商品品类"
      :visible="visible"
      :handle-close="closeCategoryDialog"
      :showFooter="false"
      :handleOpened="initProps"
    >
      <div v-if="!isSpecial">
        <div class="category-search">
          <el-form size="mini" ref="formData" :model="formData" inline>
            <el-form-item prop="categoryName" label="名称">
              <el-input
                placeholder="请输入品类名称"
                v-model="formData.categoryName"
                @keyup.enter.native="handleSerach"
              ></el-input>
            </el-form-item>
            <el-form-item prop="categoryNo" label="编码">
              <el-input
                placeholder="请输入四级类编码"
                v-model="formData.categoryNo"
                @keyup.enter.native="handleSerach"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSerach">查询</el-button>
            </el-form-item>
          </el-form>
        </div>
        <el-divider class="divider" content-position="left">条件查询结果：</el-divider>
        <div class="category-searchlist">
          <el-radio-group v-model="searchList.checkedCate" @input="handleCheckSearchList" v-loading="searchLoading">
            <el-radio
              v-for="item in searchList.dataSource"
              :label="item.categoryUuid"
              :key="item.categoryUuid"
            >
            {{ item.categoryPath }}&nbsp;&nbsp;{{ item.categoryNo }}
            </el-radio>
          </el-radio-group>
        </div>
      </div>
      <el-divider class="divider" content-position="left">品类树选择：</el-divider>
      <el-cascader-panel
        v-loading="loading"
        v-if="showPannel"
        ref="categoryPannel"
        v-model="categoryValue"
        :props="props"
        @change="handleNodeChange"
      ></el-cascader-panel>
    </basic-dialog>
  </div>
</template>
<script>
import BasicDialog from '@/components/BasicDialog';
import { queryCategoryByNoOrNameService, getByParentUuidsService } from '@/api/public';

export default {
  // 选择主营品类
  name: 'CategorySelect',
  components: {
    BasicDialog
  },
  props: {
    value: { type: String, },
    setName: { type: Boolean, default: false },
    disabled: { type: Boolean, default: false },
  },
  data () {
    return {
      searchLoading: false,
      showPannel: true,
      loading: false,
      visible: false,
      categoryName: '',
      categoryValue: '',
      props: {
        lazy: true
      },
      formData: {
        categoryName: '',
        categoryNo: '',
      },
      searchList: { // 查询列表
        dataSource: [], // 数据源
        checkedCate: '', // 勾选对象
      },
    };
  } ,
  watch: {
    value: {
      handler (val) {
        if (this.setName) {
          this.categoryName = val
        }
      },
      immediate: true,
    }
  },
  computed: {
    isSpecial () {
      return sessionStorage.supplierType == 'special'
    }
  },
  created () {
    this.initProps();
  },
  methods: {
    // 初始化lazyLoad方法
    initProps () {
      this.showPannel = true;
      this.props.lazyLoad = async (node, resolve) => {
        const { level, value } = node
        const categoryUuid = level == 0 ? 'systemUuid' : value
        this.getCategoryTreeList(categoryUuid).then(res => {
          const nodes = this.getFormatTreeNodes(level, res)
          resolve(nodes)
        })
      };
    },
    // 条件查询选择
    handleCheckSearchList (id) {
      const target = this.searchList.dataSource.find(item => item.categoryUuid == id)
      this.categoryName = target?.categoryName
      this.$emit('onSelected', target ?? {})
      if (this.$refs['categoryPannel']) {
        this.$refs['categoryPannel'].clearCheckedNodes();
      }
      this.handleChange(target?.categoryUuid)
      this.closeCategoryDialog()
    },
    // 表单-分类名称查询
    async handleSerach () {
      const hasNoCondition = Object.values(this.formData).every(val => !val)
      if (hasNoCondition) return this.$message.warning('品类名称和品类编码不能同时为空')
      const data = { ...this.formData }
      const loadingFn = state => { this.searchLoading = state }
      const res = await queryCategoryByNoOrNameService(data, loadingFn)
      if (res?.retData) {
        this.searchList.checkedCate = ''
        this.searchList.dataSource = res.retData
      }
    },
    // 获取格式化后的分类树节点数据集合
    getFormatTreeNodes (level, nodes = []) {
      const formatNodes = nodes.map(item => ({
        value: item.categoryUuid,
        label: item.categoryName,
        code: item.categoryNo,
        categoryPath: item.categoryPath,
        leaf: level >= 3,
        level: level + 1
      }))
      return formatNodes
    },
    // 获取品类树集合
    async getCategoryTreeList (categoryUuid) {
      const data = [categoryUuid]
      const loadingFn = state => { this.loading = state }
      const res = await getByParentUuidsService(data, loadingFn)
      return res?.retData ?? []
    },
    // 选择末级分类
    handleNodeChange () {
      const selectNode = this.$refs['categoryPannel'].getCheckedNodes()[0];
      if (selectNode) {
        const { code, label, value } = selectNode.data
        const infoData = {
          ...selectNode.data,
          categoryName: label,
          categoryNo: code,
          categoryUuid: value
        }
        this.categoryName = label
        this.handleChange(value)
        this.$emit('onSelected', infoData)
        this.searchList.checkedCate = '';
        this.closeCategoryDialog();
      }
    },
    // 清空已选分类
    resetSelectVal () {
      if (this.$refs.categoryPannel) {
        this.$refs.categoryPannel.clearCheckedNodes();
      }
      if (this.$refs.formData) {
        this.$refs.formData.resetFields();
      }
      this.searchList = {
        dataSource: [],
        checkedCate: ''
      }
      this.categoryName = ''
    },
    // 展示弹框
    showCategoryDialog () {
      this.visible = true;
    },
    // 关闭弹框
    closeCategoryDialog () {
      this.visible = false;
    },
    handleChange (val) {
      console.log(val)
      // 值回显父组件
      this.$emit('input', val);
      // change事件
      this.$emit('change', val);
      // this.$refs['categoryPannel'].clearCheckedNodes();
    },
    handleClear () {
      this.resetSelectVal()
      this.$emit('onSelected', null)
    }
  }
};
</script>
<style lang="less" scoped>
  /deep/.el-scrollbar__wrap {
    overflow-x: hidden;
    height: 100%;
  }
  .divider {
    margin: 10px 0;
  }
  .category-searchlist {
    .el-radio-group {
      border: 1px solid #ebeef5;
      padding-left: 5px;
      height: 200px;
      width: 100%;
      max-height: 200px;
      overflow-y: auto;
      label {
        display: block;
        line-height: 24px;
        &:first-child {
          margin-top: 10px;
        }
        &:last-child {
          margin-bottom: 10px;
        }
      }
    }
  }
</style>